package com.example.ymm.modules1.service.dd.iot;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponseBody;
import com.aliyun.tea.TeaException;
import com.example.ymm.util.EmailUtil;
import com.example.ymm.util.RedisKeyManager;
import com.example.ymm.util.RedisUtil;
import com.example.ymm.util.UtilValidate;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author zeymo
 */
@Slf4j
@Service
public class IotAccessTokenService {

    @Autowired
    IotHttpUtil iotHttpUtil;

    @Autowired
    RedisUtil redisUtil;
    

    private volatile AccessToken accessToken;

    @Getter
    @Setter
    static class AccessToken {
        private String accessToken;
        private Long expireTimestamp;
    }





    public synchronized String getAccessToken(){
        String getUrlToken=null;
        try{
            String tokenKey = RedisKeyManager.iot_access_token;
            String lockKey = RedisKeyManager.iot_access_lock;
            if(!redisUtil.hasKey(tokenKey)){
                boolean isOpen  = redisUtil.setIfAbsent(lockKey,"1",1000L, TimeUnit.SECONDS);
                if(isOpen){
                    getUrlToken=refreshAccessToken();
                    redisUtil.set(tokenKey,getUrlToken,108000L);//缓存30小时的秒数
                    return getUrlToken;
                }else{
                  //  Thread.sleep(1100L);//休眠等待执行
                    if(!redisUtil.hasKey(tokenKey)){
                        isOpen  = redisUtil.setIfAbsent(lockKey,"1",2L, TimeUnit.SECONDS);
                        if(isOpen){
                            getUrlToken=refreshAccessToken();
                            redisUtil.set(tokenKey,getUrlToken,108000L);
                            return getUrlToken;
                        }else{
                            redisUtil.remove(tokenKey);
                            getUrlToken=refreshAccessToken();
                            redisUtil.set(tokenKey,getUrlToken,108000L);
                            return getUrlToken;
                        }
                    }else{
                        return redisUtil.getString(tokenKey);
                    }
                }
            }else {
                if(UtilValidate.isNotEmpty(redisUtil.getString(tokenKey))){
                    return  redisUtil.getString(tokenKey);
                }else{
                    redisUtil.remove(tokenKey);
                    redisUtil.remove(lockKey);
                    return getAccessToken();
                }

            }
        }catch (Exception e){
            return null;
        }
    }

    private String refreshAccessToken() {



        try {
            JSONObject param = new JSONObject();
            param.put("username", "hlzbjt");
            param.put("password", "123456");
            String token = iotHttpUtil.httpPostLogin(param);
            AccessToken accessToken = new AccessToken();
            accessToken.setAccessToken(token);
            this.accessToken = accessToken;
            log.info(" 亮灯token获取成功:", token);
            return token;
        } catch (TeaException e) {
            log.error("AccessTokenService_getTokenFromRemoteServer getAccessToken throw " +
                    "TeaException, errCode={}, errorMessage={}", e.getCode(), e.getMessage(), e);
            EmailUtil.sendEmail("1055162826@qq.com","获取 亮灯 token异常errCode:"+e.getCode(),e.getMessage());
            return null;
        } catch (Exception e) {
            log.error("AccessTokenService_getTokenFromRemoteServer getAccessToken throw Exception", e);
            EmailUtil.sendEmail("1055162826@qq.com","获取 亮灯_异常token:",e.getMessage());
            return null;
        }
    }



}
